package finance

class HistoricalStatisticsController {
    def historicalQueryService
    def frequenceService
    def chiSquareService
    def theoDistService
    def descriptiveStatisticsService
    def loMacKinlayService
    def waldWolfowitzService
    def entropyService
    def polynomialFitService
    
    def calcFrequence(vals, fieldVar) {
        def frequence = frequenceService.frequence(vals)
        
        return frequence
    }
    
    def doubleValues(map) {
        return map.values() as double[]
    }
    
    def doubleKeys(map) {
        def keys = map.keySet()	
        def doubleKeys = []
        keys.each {  doubleKeys << Double.valueOf(it) }
        
        return doubleKeys
    }
    
    def makeResponse(vals) {
        def frequence = calcFrequence(vals, params.fieldVar)
        def statsMap = descriptiveStatisticsService.stats(vals)
        def normalExpected = theoDistService.gaussExpected(statsMap["mean"],
                statsMap["stddev"],  doubleKeys(frequence))
        
        def chi2 = chiSquareService.chiSquare(normalExpected, 
                frequence.values())
        def rejections = chiSquareService.canBeRejected(normalExpected, frequence.values())	
        
        def lomac = loMacKinlayService.ratio(vals)
        def waldWolf = waldWolfowitzService.Z(vals as double[])
        
        def sampleEntropy = entropyService.entropy(frequence.values())
        def naturalEntropy = entropyService.normalEntropy(statsMap["stddev"])
        
        def levyConstant = 1
        def levyEntropy = entropyService.levyEntropy( levyConstant )
        def levyExpected = theoDistService.levyExpected( levyConstant, doubleKeys(frequence), statsMap["mean"])
        
        def levyRejections = chiSquareService.canBeRejected( levyExpected, frequence.values())
        def levyChi2 = chiSquareService.chiSquare(levyExpected, 
                frequence.values())
        
        def fits = []
        
        for(degree in 1..6)
            fits << polynomialFitService.fit(degree, vals) 
        
        
        return [chiSquare : chi2, statsMap : statsMap, 
            rejections : rejections,
            lomac : lomac,
            waldWolf : waldWolf,
            sampleEntropy : sampleEntropy,
            naturalEntropy: naturalEntropy,
            levyEntropy : levyEntropy,
            levyChi2 : levyChi2,
            levyRejections : levyRejections,
            fits : fits]
    }
    
    def index = { 
        if(params.fieldVar != null) {
            def vals = historicalQueryService.queryVals( params.select1, params.fieldVar);
            return makeResponse(vals)
        }
    }
}
